package com.cvnert.testplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cvnert.testplatform.domain.*;
import com.cvnert.testplatform.domain.vo.VersionVo;
import com.cvnert.testplatform.mapper.*;
import com.cvnert.testplatform.service.VersionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author pc
* @description 针对表【version】的数据库操作Service实现
* @createDate 2024-03-24 14:48:29
*/
@Service
public class VersionServiceImpl extends ServiceImpl<VersionMapper, Version> implements VersionService{
    @Resource
    private VersionMapper versionMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private TestCaseMapper testCaseMapper;

    @Resource
    private  DefectMapper defectMapper;

    @Resource
    private TaskVersionMapper taskVersionMapper;


    @Resource
    private DefectVersionMapper defectVersionMapper;

    @Resource
    private  TastCaseVersionMapper taskCaseVersionMapper;
    /**
     * 获取版本信息
     * @param versionVo 版本实体
     * @return
     */
    @Override
    public Object getList(VersionVo versionVo) {
        HashMap<String, Object> res = new HashMap<>();
        if (versionVo == null) {
            res.put("state", false);
            res.put("msg", "参数不允许为空！");
            return res;
        }
        // 分页查询
        Page<Version> page = new Page<>(versionVo.getPageNum(), versionVo.getPageSize());
        QueryWrapper<Version> wrapper = new QueryWrapper<>();
        if (versionVo.getVersion() != null && !versionVo.getVersion().equals("")){
            wrapper.eq("version", versionVo.getVersion());
        }
        if (versionVo.getVersionname() != null && !versionVo.getVersionname().equals("")){
            wrapper.like("versionName", versionVo.getVersionname());
        }
        // 把传过来的username转化成uid
        if (versionVo.getUsername() != null && !versionVo.getUsername().equals("")){
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", versionVo.getUsername()));
            if (user != null) {
                wrapper.eq("uid", user.getId());

            }
        }
        // 查询版本信息中的所有uid字段并且转化成user
        List<Integer> uid =  versionMapper.selectList(wrapper).stream()
              .map(Version::getUid)
              .collect(Collectors.toList());
        if (uid.size() == 0){
            res.put("state", true);
            res.put("msg", "没有查询到数据");
            return res;
        }
        List<User> users = userMapper.selectBatchIds(uid);
        Page<Version> versionPage = versionMapper.selectPage(page, wrapper);

        // 获取每个版本的uid和用户的id相同的用户
        versionPage.getRecords().forEach(version -> {
            ArrayList<User> userArr = new ArrayList<>(); // 移动到循环内部并重新初始化
            users.forEach(user -> {
                if (user.getId().equals(version.getUid())) {
                    userArr.add(user);
                }
            });
            version.setUser(userArr); // 移动到循环外部
        });

        // 获取库中所有的vid
        List<Integer> vids = versionMapper.selectList(wrapper).stream()
                .map(Version::getVid)
                .collect(Collectors.toList());
        // 通过vid查询task_version表中的所有tid
        List<Integer> tids = taskVersionMapper.selectList(new QueryWrapper<>()).stream()
                .filter(taskVersion -> vids.contains(taskVersion.getVid()))
                .map(taskVersion -> taskVersion.getTid())
                .collect(Collectors.toList());
        ArrayList<Task> tasks1 = new ArrayList<>();
        if (tids.size() != 0){
            // 通过tids查询task表中的所有任务
            List<Task> tasks = taskMapper.selectBatchIds(tids);
            tasks1.addAll(tasks);
        }
        // 通过vid查询defect_version表中的所有did
        List<Integer> dids = defectVersionMapper.selectList(new QueryWrapper<>()).stream()
                .filter(defectVersion -> vids.contains(defectVersion.getVid()))
                .map(defectVersion -> defectVersion.getDid())
                .collect(Collectors.toList());
        ArrayList<Defect> defects1 = new ArrayList<>();

        if (dids.size() != 0){
            // 通过dids查询defect表中的所有缺陷
            List<Defect> defects = defectMapper.selectBatchIds(dids);
            defects1.addAll(defects);
        }

        // 通过vid查询task_case_version表中的所有cid
        List<Integer> cids = taskCaseVersionMapper.selectList(new QueryWrapper<>()).stream()
                .filter(taskCaseVersion -> vids.contains(taskCaseVersion.getVid()))
                .map(taskCaseVersion -> taskCaseVersion.getCid())
                .collect(Collectors.toList());
        ArrayList<TestCase> testCases1 = new ArrayList<>();
        if (cids.size() != 0){
            // 通过cids查询test_case表中的所有用例
            List<TestCase> testCases = testCaseMapper.selectBatchIds(cids);
            testCases1.addAll(testCases);
        }



        versionPage.getRecords().forEach(version -> {
            // 把tasks放到task里面去
            version.setTask(tasks1);
            version.setCases(testCases1);
            version.setDefects(defects1);
        });


        res.put("state", true);
        res.put("msg", "查询成功");
        res.put("data", versionPage);
        return res;
    }

    /**
     * 新增版本信息
     * @param version 版本信息
     * @return
     */
    @Override
    public Object addVersion(Version version) {
        HashMap<String, Object> res = new HashMap<>();
        if (version == null||version.getVersion() == null||version.getVersion().equals("")) {
            res.put("state", false);
            res.put("msg", "版本号不允许为空！");
            return res;
        }
        if (version.getVersionname().equals("")){
            res.put("state", false);
            res.put("msg", "版本名称不允许为空！");
            return res;
        }
        version.setCreatetime(LocalDateTime.now());
        int insert = versionMapper.insert(version);
        if (insert == 1) {
            Version version1 = versionMapper.selectById(version.getId());
            version1.setVid(version1.getId());
            versionMapper.updateById(version1);
            res.put("state", true);
            res.put("msg", "新增成功");

        } else {
            res.put("state", false);
            res.put("msg", "新增失败");
        }
        return res;
    }

    /**
     * 删除版本
     * @param vid
     * @return
     */
    @Override
    public Object deleteVersion(Integer vid) {
        HashMap<String, Object> res = new HashMap<>();
        // 判断版本是否存在
        Version version = versionMapper.selectById(vid);
        if (version == null) {
            res.put("state", false);
            res.put("msg", "版本不存在");
            return res;
        }
        int i = versionMapper.deleteById(vid);
        if (i == 1) {
            res.put("state", true);
            res.put("msg", "删除成功");
        } else {
            res.put("state", false);
            res.put("msg", "删除失败");
        }
        return res;
    }

    @Override
    public Object updateVersion(Version version) {
        HashMap<String, Object> res = new HashMap<>();
        if (version == null||version.getId() == null) {
            res.put("state", false);
            res.put("msg", "版本id不允许为空！");
            return res;
        }
        // 判断版本是否存在
        Version version1 = versionMapper.selectById(version.getId());
        if (version1 == null) {
            res.put("state", false);
            res.put("msg", "版本不存在");
            return res;
        }
        int i = versionMapper.updateById(version);
        if (i == 1) {
            res.put("state", true);
            res.put("msg", "修改成功");
        } else {
            res.put("state", false);
            res.put("msg", "修改失败");
        }
        return res;
    }

    @Override
    public Object getVersionDetail(Integer vid) {
        HashMap<String, Object> res = new HashMap<>();
        Version version = versionMapper.selectById(vid);
        if (version == null) {
            res.put("state", false);
            res.put("msg", "版本不存在");
            return res;
        }
        Integer uid = version.getUid();
        User user = userMapper.selectById(uid);
        ArrayList<User> users = new ArrayList<>();
        users.add(user);
        version.setUser(users);
        ArrayList<Task> tasks = new ArrayList<>();
        ArrayList<Defect> defects = new ArrayList<>();
        ArrayList<TestCase> testCases = new ArrayList<>();

        // 通过vid查询task_version表中的所有tid
        List<Integer> tids = taskVersionMapper.selectList(new QueryWrapper<>()).stream()
                .filter(taskVersion -> taskVersion.getVid().equals(vid))
                .map(taskVersion -> taskVersion.getTid())
                .collect(Collectors.toList());
        if (tids.size()==0){
            res.put("state", true);
            res.put("msg", "该版本下没有任务");

        }else{
            List<Task> taskss = taskMapper.selectBatchIds(tids);
            if (tasks == null) {
                tasks = new ArrayList<>();
            }else {
                tasks.addAll(taskss);
            }
        }
        // 通过tids查询task表中的所有任务


        // 通过vid查询defect_version表中的所有did
        List<Integer> dids = defectVersionMapper.selectList(new QueryWrapper<>()).stream()
                .filter(defectVersion -> defectVersion.getVid().equals(vid))
                .map(defectVersion -> defectVersion.getDid())
                .collect(Collectors.toList());
        if (dids.size()==0){
            res.put("state", true);
            res.put("msg", "该版本下没有缺陷");
        }
       else if (dids.size()==0 && tids.size()==0){
            res.put("state", true);
            res.put("msg", "该版本下没有任务和缺陷");
        }
        else{
            // 通过dids查询defect表中的所有缺陷
            List<Defect> defectss = defectMapper.selectBatchIds(dids);
            if (defects == null) {
                defects = new ArrayList<>();
            }else {
                defects.addAll(defectss);
            }
        }


        // 通过vid查询task_case_version表中的所有cid
        List<Integer> cids = taskCaseVersionMapper.selectList(new QueryWrapper<>()).stream()
                .filter(taskCaseVersion -> taskCaseVersion.getVid().equals(vid))
                .map(taskCaseVersion -> taskCaseVersion.getCid())
                .collect(Collectors.toList());
        if (cids.size()==0){
            res.put("state", true);
            res.put("msg", "该版本下没有用例");
        }
       else if (cids.size()==0 && tids.size()==0){
            res.put("state", true);
            res.put("msg", "该版本下没有任务和用例");
        }
       else if (cids.size()==0 && tids.size()==0 && dids.size()==0){
            res.put("state", true);
            res.put("msg", "该版本下没有任务和用例和缺陷");
        }
       else {
            // 通过cids查询test_case表中的所有用例
            List<TestCase> testCasess = testCaseMapper.selectBatchIds(cids);
            if (testCases == null) {
                testCases = new ArrayList<>();
            }else {
                testCases.addAll(testCasess);
            }
        }
        version.setTask(tasks);
        version.setCases(testCases);
        version.setDefects(defects);
        
        res.put("state", true);
        res.put("msg", "查询成功");
        res.put("data", version);
        return res;
    }
}




